﻿using System;
using System.IO;
using System.Web;

namespace ProMoniter.AppPage
{
    /// <summary>
    /// 用于响应文件上传的请求
    /// </summary>
    public partial class FileHandler : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SaveUploadedFile(Request.Files);
            }
        }

        public void SaveUploadedFile(HttpFileCollection httpFileCollection)
        {
            foreach (string fileName in httpFileCollection)
            {
                HttpPostedFile file = httpFileCollection.Get(fileName);
                //Save file content goes here
                if (file != null && file.ContentLength > 0)
                {
                    var originalDirectory = new DirectoryInfo(string.Format("{0}UploadFiles", Server.MapPath(@"\")));
                    string fullPath = System.IO.Path.Combine(originalDirectory.ToString(), "ExcelFiles");

                    if (!System.IO.Directory.Exists(fullPath))
                        System.IO.Directory.CreateDirectory(fullPath);

                    var fileNameUpload = file.FileName;

                    int addIndex = 1;       //避免文件重名的方法
                    while (File.Exists(string.Format("{0}\\{1}", fullPath, fileNameUpload)))
                    {
                        addIndex++;
                        int indexSplit = file.FileName.LastIndexOf(".");
                        string name = file.FileName.Substring(0, indexSplit);
                        string extname = file.FileName.Substring(indexSplit);
                        fileNameUpload = string.Format("{0}_{1}{2}", name, addIndex, extname);
                    }

                    var path = string.Format("{0}\\{1}", fullPath, fileNameUpload);
                    file.SaveAs(path);

                    //上传实际的上传保存文件名至cookies
                    Response.Cookies[file.FileName].Value = fileNameUpload;
                    Response.Cookies[file.FileName].Expires = DateTime.Now.AddSeconds(90);
                }
            }
        }
    }
}